package cn.com.netedge.iot.frontend.biz.mq;

import cn.com.netedge.iot.frontend.biz.protocol.AbstractHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import cn.com.netedge.iot.common.dataobject.CmdMsgResp;
import cn.com.netedge.iot.common.dataobject.ReceiveFrame;
import cn.com.netedge.iot.common.exception.BizException;
import cn.com.netedge.iot.common.mq.MqMessageListener;

@Component
public abstract class BaseReceiveMessageConsumer extends MqMessageListener {
    private static Logger logger = LoggerFactory.getLogger(BaseReceiveMessageConsumer.class);

    protected CmdMsgResp processMessage(AbstractHandle dealHandle, ReceiveFrame frame) {
        //解析报文
        CmdMsgResp resp;
        boolean isError = false;
        try {
            resp = dealHandle.decoder(frame);
        } catch (BizException e) {
            logger.error("consume message error. frame: {}, error: ", JSON.toJSONString(frame), e);
            resp = replyError(e.getMessage());
            isError = true;
        } catch (Exception e) {
            logger.error("consume message error. frame: {}, error: ", JSON.toJSONString(frame), e);
            resp = replyError(e.getMessage());
            isError = true;
        }
        if (resp == null) {
            logger.error("consume message error. frame: {}, error: decode failed, resp object is null ", JSON.toJSONString(frame));
            resp = replyError("decode failed, resp object is null");
            isError = true;
        }
        //decoder方法中已处理异常，将success设为false
        if (resp.isSuccess()) {
            resp.setSuccess(!isError);
        }
        return resp;
    }
    
    protected CmdMsgResp replyError(String message) {
        CmdMsgResp resp = new CmdMsgResp();
        resp.setSuccess(false);
        resp.setMessage("报文解析出错:" + message);
        return resp;
    }
}
